package com.java.controller;

import com.java.dto.ApplyDTO;
import com.java.dto.MediaAccountDTO;
import com.java.model.*;
import com.java.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/apply")
public class ApplyController {

    String urlpat;

    @Autowired
    private ApplyService applyService;

    @Autowired
    private AdvertisersAccountService advertisersAccountService;

    @Autowired
    private PlatformService platformService;

    @Autowired
    private ProductService productService;

    @Autowired
    private BookingService bookingService;

    @Autowired
    private MediaAccountService mediaAccountService;

    /**
     * 跳转自媒体投稿申请单
     * @return
     */
    @GetMapping("/list")
    public String list(Model model, HttpServletRequest request) {
        // 在session域中拿取自媒体id
        MediaAccount user = (MediaAccount) request.getSession().getAttribute("user");
        model.addAttribute("id", user.getId());

//        // 投放平台
        List<Platform> platform = platformService.toList();
        model.addAttribute("platform", platform);
//        // 所属行业
        List<Product> product = productService.toList();
        model.addAttribute("product", product);

        List<Apply> applies = applyService.toList();
        model.addAttribute("applies", applies);
        return "/apply/list";
    }

    /**
     * 跳转管理员投稿申请单
     * @return
     */
    @GetMapping("/applyList")
    public String applyList(Model model) {
//        // 投放平台
        List<Platform> platform = platformService.toList();
        model.addAttribute("platform", platform);
//        // 所属行业
        List<Product> product = productService.toList();
        model.addAttribute("product", product);

        List<Apply> applies = applyService.toList();
        model.addAttribute("applies", applies);
        return "/applyTOW/list";
    }

    /**
     * 自媒体投放查询列表
     * @param apply
     * @return
     */
    @PostMapping("/toList")
    @ResponseBody
    public Result toList(Apply apply) {
        return applyService.list(apply);
    }

    /**
     * 管理员投放查询列表
     * @param apply
     * @return
     */
    @PostMapping("/adminList")
    @ResponseBody
    public Result adminList(Apply apply) {
        return applyService.adminList(apply);
    }

    /**
     * 自媒体审核
     * @param apply
     * @return
     */
    @PostMapping("/agree")
    @ResponseBody
    public Result agree(Apply apply) {
        return applyService.modifyAudit(apply);
    }

    /**
     * 管理员审核
     * @param apply
     * @return
     */
    @PostMapping("/adminAgree")
    @ResponseBody
    public Result adminAgree(Apply apply) {
        /*生成投放预约单*/
        Booking booking = new Booking();
        booking.setApplyId(apply.getId());
        booking.setStatus(1);
        booking.setCreateTime(new Date());
        booking.setRemark("谢谢您的选择");
        bookingService.addOrder(booking);
        return applyService.adminAgree(apply);
    }

    /**
     * 拒绝操作
     * @param apply
     * @return
     */
    @PostMapping("/refused")
    @ResponseBody
    public Result refused(Apply apply) {
        return applyService.refused(apply);
    }

    /**
     * 提交投稿申请单
     * @param applyDTO
     * @param request
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    public Result save(ApplyDTO applyDTO, BigDecimal price, HttpServletRequest request, Model model) {
        //查出自己还有多少余额
        AdvertisersAccount advertisersAccount = (AdvertisersAccount) request.getSession().getAttribute("advertisersAccount");
        AdvertisersAccount recharge = advertisersAccountService.recharge(advertisersAccount.getId());

        //把BigDecimal转换为int类型
        int p = price.intValue();//投放需要的钱
        int r = recharge.getAdvertisersWallet().getAvailableBalance().intValue();//余额

        //判断自己的余额够不够
        if (r < p){//余额充足
            return Result.error("您的余额不足");
        }

        //余额充足的话
        int peices = r - p;//扣完剩余多少钱
        BigDecimal bigDecimal = BigDecimal.valueOf(peices);//转换为bigDecimal类型
        //修改余额
        AdvertisersWallet advertisersWallet = new AdvertisersWallet();
        advertisersWallet.setAvailableBalance(bigDecimal);
        advertisersWallet.setId(advertisersAccount.getId());
        advertisersAccountService.money(advertisersWallet);

        //获取冻结了的金额
        BigDecimal b = recharge.getAdvertisersWallet().getBlockedBalance();
        int blockedBalance = b.intValue();
        //把减去的的钱加在冻结金额哪里
        int frozen = blockedBalance + p;
        BigDecimal bigDecimal1 = BigDecimal.valueOf(frozen);//转换为bigDecimal类型
        //修改冻结金额
        advertisersWallet.setBlockedBalance(bigDecimal1);
        advertisersWallet.setAdsId(advertisersAccount.getId());
        advertisersAccountService.frozen(advertisersWallet);


        Apply apply = new Apply();
//        applyMapperapply.setPlatformId(applyDTO.getPlatformId());
        apply.setPlatformId(applyDTO.getPlatformId());
        apply.setTheme(applyDTO.getTheme());
        apply.setBrand(applyDTO.getBrand());
        apply.setCompUrl(applyDTO.getCompUrl());
        apply.setProductType(applyDTO.getProductType());
        apply.setPtName(applyDTO.getProductName());
        apply.setProductUrl(applyDTO.getProductUrl());
        apply.setDetail(applyDTO.getDetail());
        apply.setCreateTime(new Date());
        apply.setStartTime(new Date());
        apply.setProof(urlpat);
        apply.setStatus(1);

        //拿到广告主的id
        AdvertisersAccount advertiser = (AdvertisersAccount) request.getSession().getAttribute("advertisersAccount");
        Object priceId = request.getSession().getAttribute("priceId");
        apply.setAdsId(advertiser.getId());
        apply.setPriceId((Integer) priceId);
        apply.setAccountId(applyDTO.getId());

        return applyService.save(apply);
    }


    /**
     * 富文本
     * @param request
     * @param file
     * @return
     */
    @RequestMapping("/file")
    @ResponseBody
    public Map<String,Object> felt(HttpServletRequest request, @RequestParam MultipartFile file) {

        Map<String,Object> mv=new HashMap<String, Object>();
        Map<String,String> mvv=new HashMap<String, String>();
        try {
            String rootPath = request.getSession().getServletContext().getRealPath("/image/");
            Calendar date = Calendar.getInstance(); //Calendar.getInstance()是获取一个Calendar对象并可以进行时间的计算，时区的指定
            String originalFile = file.getOriginalFilename(); //获得文件最初的路径
            String uuid = UUID.randomUUID().toString();    //UUID转化为String对象
            String newfilename=date.get(Calendar.YEAR)+""+(date.get(Calendar.MONTH)+1)+""+date.get(Calendar.DATE)+uuid.replace("-", "")+originalFile;
            //得到完整路径名
            File newFile = new File(rootPath+newfilename);
            /*文件不存在就创建*/
            if(!newFile.getParentFile().exists()){
                newFile.getParentFile().mkdirs();
            }
            String filename=originalFile.substring(0, originalFile.indexOf("."));
            System.out.println(originalFile);
            System.out.println(filename);
            file.transferTo(newFile);
            System.out.println("newFile : "+newFile);
            String urlpat= "/image/"+ newfilename;
            mvv.put("src", urlpat);
            mvv.put("title",newfilename);
            mv.put("code", 0);
            mv.put("msg", "上传成功");
            mv.put("data", mvv);
            return mv;
        } catch (Exception e) {
            e.printStackTrace();
            mv.put("success", 1);
            return mv;
        }
    }


    /**
     * 上传图片
     * @param request
     * @param file
     * @return
     */
    @RequestMapping("/files")
    @ResponseBody
    // 文件上传
    public Map<String,Object> felts(HttpServletRequest request, @RequestParam MultipartFile file) {

        Map<String,Object> mv=new HashMap<String, Object>();
        Map<String,String> mvv=new HashMap<String, String>();
        try {
            String rootPath = request.getSession().getServletContext().getRealPath("/image/");
            Calendar date = Calendar.getInstance(); //Calendar.getInstance()是获取一个Calendar对象并可以进行时间的计算，时区的指定
            String originalFile = file.getOriginalFilename(); //获得文件最初的路径
            String uuid = UUID.randomUUID().toString();    //UUID转化为String对象
            String newfilename=date.get(Calendar.YEAR)+""+(date.get(Calendar.MONTH)+1)+""+date.get(Calendar.DATE)+uuid.replace("-", "")+originalFile;
            //得到完整路径名
            File newFile = new File(rootPath+newfilename);
            /*文件不存在就创建*/
            if(!newFile.getParentFile().exists()){
                newFile.getParentFile().mkdirs();
            }
            String filename=originalFile.substring(0, originalFile.indexOf("."));
            System.out.println(originalFile);
            System.out.println(filename);
            file.transferTo(newFile);
            System.out.println("newFile : "+newFile);
            urlpat= "/image/"+ newfilename;
            mvv.put("src", urlpat);
            mvv.put("title",newfilename);
            mv.put("code", 0);
            mv.put("msg", "上传成功");
            mv.put("data", mvv);
            return mv;
        } catch (Exception e) {
            e.printStackTrace();
            mv.put("success", 1);
            return mv;
        }
    }

    /**
     * 自媒体资料修改
     * @return
     */
    @PostMapping("/modification")
    @ResponseBody
    public Result modification(MediaAccountDTO mediaAccountDTO) {
        MediaAccount mediaAccount = new MediaAccount();
        mediaAccount.setUsername(mediaAccountDTO.getUsername()); //自媒体帐号
        mediaAccount.setAccountName(mediaAccountDTO.getAccountName()); //自媒体帐号的名字
        mediaAccount.setHeadImg(urlpat); //头像图片
        mediaAccount.setUrl(mediaAccountDTO.getUrl()); //帐号详情的url
        mediaAccount.setOwner(mediaAccountDTO.getOwner()); //所属平台
        mediaAccount.setDetailImg(mediaAccountDTO.getDetailImg()); //帐号详情图片
        mediaAccount.setId(mediaAccountDTO.getId());

        return mediaAccountService.modification(mediaAccount);
    }
}
